﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TBA.PGB.DAO;
using TBA.PGB.DAO.AZREntity.Entity;
using TBA.PGB.DAO.DBEntity;
using TBA.PGB.Business;

public partial class secure_zk_PGB_Assignment_AddIB_FunctionInputs : System.Web.UI.UserControl
{
    #region Properties
    //public delegate void SelectChangeEventHandler(object sender, EventArgs e);
    //public event SelectChangeEventHandler SelectChange;

    //public delegate void ClickEventHandler(object sender, EventArgs e);
    //public event ClickEventHandler Click;

    //Connectionstring Property
    public String ConnectionString
    {
        get
        {
            if (ViewState["ConnectionString"] == null)
            {
                throw new NullReferenceException("ConnectionString");
            }
            else
            {
                return (String)ViewState["ConnectionString"].ToString();
            }
        }
        set
        {
            ViewState["ConnectionString"] = value;
        }
    }

    /// <summary>
    /// Example: firstZZP/secondZZP
    /// </summary>
    public String ZZPType
    {
        get
        {
            if (ViewState["ZZPType"] == null)
            {
                throw new NullReferenceException("ZZPType");
            }
            else
            {
                return (String)ViewState["ZZPType"].ToString();
            }
        }
        set
        {
            ViewState["ZZPType"] = value;
        }
    }

    /// <summary>
    /// True: new Indication; False: old Indication;
    /// </summary>
    public Boolean IndicationStatus
    {
        get
        {
            if (ViewState["IndicationStatus"] == null)
            {
                throw new NullReferenceException("IndicationStatus");
            }
            else
            {
                return (Boolean)ViewState["IndicationStatus"];
            }
        }
        set
        {
            ViewState["IndicationStatus"] = value;
        }
    }

    public Indicatiebesluit SourceIndication
    {
        get
        {
            if (ViewState["SourceIndication"] == null)
            {
                return null;
            }
            else
            {
                return (Indicatiebesluit)ViewState["SourceIndication"];
            }
        }
        set
        {
            ViewState["SourceIndication"] = value;
        }
    }

    public List<ViewZTWFunction> SourceFunctions
    {
        get
        {
            if (ViewState["SourceFunctions"] == null)
            {
                return null;
            }
            else
            {
                return (List<ViewZTWFunction>)ViewState["SourceFunctions"];
            }
        }
        set
        {
            ViewState["SourceFunctions"] = value;
        }
    }

    public GridView SourceGridView
    {
        get
        {
            if (ViewState["SourceGridView"] == null)
            {
                return null;
            }
            else
            {
                return (GridView)ViewState["SourceGridView"];
            }
        }
        set
        {
            ViewState["SourceGridView"] = value;
        }
    }

    public HiddenField SourceHiddenRowindex
    {
        get
        {
            if (ViewState["SourceHiddenRowindex"] == null)
            {
                return null;
            }
            else
            {
                return (HiddenField)ViewState["SourceHiddenRowindex"];
            }
        }
        set
        {
            ViewState["SourceHiddenRowindex"] = value;
        }
    }
    #endregion

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            LoadSourceDatas();
        }
    }

    #region Load Function Inputs Datas
    public void LoadSourceDatas()
    {
        using (Indicatiebesluit indi = SourceIndication)
        {
            //Load the input controls
            LoadStep4DDLists(indi);
            LoadStep4Durations(indi);
            LoadStep4ExtraInformation(ddl_Functie.SelectedValue,
                ddl_Klasse.SelectedValue,
                ddl_Klasse.Items[ddl_Klasse.Items.Count - 1].Value);

           SourceGridView.DataSource = SourceFunctions;
            SourceGridView.DataBind();

            LoadStep4InputStatus(true, IndicationStatus);
        }
    }

    private void LoadStep4InputStatus(Boolean status, Boolean isNewIndication)
    {
        btn_AddFunc.Enabled = isNewIndication ? status : false;
        btn_UpdateFunc.Enabled = isNewIndication ? !status : false;
        ddl_IndicationType.Enabled = isNewIndication ? status : false;
        SourceGridView.Enabled = isNewIndication ? status : false;
    }

    private void LoadStep4DDLists(Indicatiebesluit pageIndication)
    {
        bindLists(IBManuallyHandler.GetFunctions(
            ZZPType == "secondZZP" ? pageIndication.SecondZZP : pageIndication.ZZP, ConnectionString),
                  ddl_Functie);

        bindLists(IBManuallyHandler.GetActivies(ddl_Functie.SelectedValue,
            ZZPType == "secondZZP" ? pageIndication.SecondZZP : pageIndication.ZZP, ConnectionString),
                  ddl_Activiteit);

        bindLists(IBManuallyHandler.GetClasses(ddl_Functie.SelectedValue, ConnectionString),
                      ddl_Klasse);
    }

    private void bindLists(Dictionary<String, String> datasource, DropDownList ddlist)
    {
        ddlist.Items.Clear();

        foreach (String key in datasource.Keys)
        {
            ddlist.Items.Add(new ListItem(datasource[key], key));
        }
    }

    private void LoadStep4Durations(Indicatiebesluit pageIndication)
    {
        WDC_Ingangsdatum.MinDate = ZZPType == "secondZZP" ? pageIndication.SecondZZPStartDate.Value : pageIndication.ZZPStartDate;
        WDC_Endiedatum.MinDate = ZZPType == "secondZZP" ? pageIndication.SecondZZPStartDate.Value : pageIndication.ZZPStartDate;

        WDC_Ingangsdatum.MaxDate = ZZPType == "secondZZP" ? pageIndication.SecondZZPEndDate.Value : pageIndication.ZZPEndDate.Value;
        WDC_Endiedatum.MaxDate = ZZPType == "secondZZP" ? pageIndication.SecondZZPEndDate.Value : pageIndication.ZZPEndDate.Value;

        WDC_Ingangsdatum.Value = ZZPType == "secondZZP" ? pageIndication.SecondZZPStartDate.Value : pageIndication.ZZPStartDate;
        WDC_Endiedatum.Value = ZZPType == "secondZZP" ? pageIndication.SecondZZPEndDate.Value : pageIndication.ZZPEndDate.Value;
    }

    private void LoadStep4ExtraInformation(String selectedFunctionCode, String selectedClassCode, String maxClassCode)
    {
        txt_Number.Text = String.Empty;
        //dbo.[21_Functie].Tijdseenheid is null
        if (selectedFunctionCode == "61" || selectedFunctionCode == "62" || selectedFunctionCode == "71"
            || selectedFunctionCode == "72" || selectedClassCode != maxClassCode)
        {
            txt_Number.Enabled = false;
            ddl_timeUnit.Enabled = false;
        }
        else
        {
            txt_Number.Enabled = true;

            //dbo.[21_Functie].Tijdseenheid = 13; [Day] FK to dbo.[21_Tijdseenheid]
            if (selectedClassCode == "12" || selectedClassCode == "52" || selectedClassCode == "82")
            {
                ddl_timeUnit.SelectedValue = "13";
            }

            //dbo.[21_Functie].Tijdseenheid = 04; [Hour] FK to dbo.[21_Tijdseenheid]
            if (selectedClassCode == "11" || selectedClassCode == "21" || selectedClassCode == "31" ||
                selectedClassCode == "41" || selectedClassCode == "51" || selectedClassCode == "81")
            {
                ddl_timeUnit.SelectedValue = "04";
            }

            ddl_timeUnit.Enabled = false;
        }

        REV_number.Enabled = txt_Number.Enabled;
        RFV_number.Enabled = txt_Number.Enabled;

        setTextboxDisabledColor();
    }

    private void setTextboxDisabledColor()
    {
        if (!txt_Number.Enabled)
        {
            txt_Number.ControlStyle.BorderColor = System.Drawing.Color.White;
        }
    }
    #endregion

    #region Dropdownlists Actions
    protected void ddl_Functie_SelectedIndexChanged(object sender, EventArgs e)
    {
        bindLists(IBManuallyHandler.GetActivies(
            ((DropDownList)sender).SelectedValue, ZZPType == "secondZZP" ? SourceIndication.SecondZZP : SourceIndication.ZZP, ConnectionString),
            ddl_Activiteit);

        bindLists(IBManuallyHandler.GetClasses(
            ((DropDownList)sender).SelectedValue, ConnectionString), ddl_Klasse);

        LoadStep4ExtraInformation(((DropDownList)sender).SelectedValue,
            ddl_Klasse.SelectedValue, ddl_Klasse.Items[ddl_Klasse.Items.Count - 1].Value);

        //if (SelectChange != null)
        //{ SelectChange(this, e); }
    }

    protected void ddl_Klasse_SelectedIndexChanged(object sender, EventArgs e)
    {
        LoadStep4ExtraInformation(ddl_Functie.SelectedValue,
            ((DropDownList)sender).SelectedValue,
            ((DropDownList)sender).Items[((DropDownList)sender).Items.Count - 1].Value);

        //if (SelectChange != null)
        //{ SelectChange(this, e); }
    }
    #endregion

    #region Buttons Actions
    private bool validatedFuncOverlap(List<ViewZTWFunction> pageFuncList, DateTime startDate, DateTime endDate, String funcCode)
    {
        if (SourceHiddenRowindex.Value.ToString().Trim() == String.Empty)
        {
            return pageFuncList.Exists(delegate(ViewZTWFunction fFunc)
            {
                return fFunc.Functiecode.Code == funcCode
                    && (((fFunc.GewensteStartdatum.CompareTo(startDate) < 0 || fFunc.GewensteStartdatum.CompareTo(startDate) == 0)
                        && (fFunc.GewensteEinddatum.Value.CompareTo(startDate) > 0 || fFunc.GewensteEinddatum.Value.CompareTo(startDate) == 0))
                    || ((fFunc.GewensteEinddatum.Value.CompareTo(endDate) > 0 || fFunc.GewensteEinddatum.Value.CompareTo(endDate) == 0)
                        && (fFunc.GewensteStartdatum.CompareTo(endDate) < 0 || fFunc.GewensteStartdatum.CompareTo(endDate) == 0)));
            });
        }
        else
        {
            return pageFuncList.FindAll(delegate(ViewZTWFunction fFunc)
            {
                return fFunc.Functiecode.Code == funcCode
                    && (((fFunc.GewensteStartdatum.CompareTo(startDate) < 0 || fFunc.GewensteStartdatum.CompareTo(startDate) == 0)
                        && (fFunc.GewensteEinddatum.Value.CompareTo(startDate) > 0 || fFunc.GewensteEinddatum.Value.CompareTo(startDate) == 0))
                    || ((fFunc.GewensteEinddatum.Value.CompareTo(endDate) > 0 || fFunc.GewensteEinddatum.Value.CompareTo(endDate) == 0)
                        && (fFunc.GewensteStartdatum.CompareTo(endDate) < 0 || fFunc.GewensteStartdatum.CompareTo(endDate) == 0)));
            }).Count > 1;
        }
    }

    protected void cstV_Ingangsdatum_ServerValidate(object source, ServerValidateEventArgs args)
    {
        args.IsValid = !validatedFuncOverlap((List<ViewZTWFunction>)SourceFunctions,
            DateTime.Parse(WDC_Ingangsdatum.Value.ToString()), new DateTime(),
            ddl_Functie.SelectedValue);

        if (args.IsValid)
        {
            cstV_Ingangsdatum.ErrorMessage = "Ingangsdatum is overlappend met toegevoegde functies!";
        }

    }

    protected void cstV_Endiedatum_ServerValidate(object source, ServerValidateEventArgs args)
    {
        args.IsValid = !validatedFuncOverlap((List<ViewZTWFunction>)SourceFunctions,
            new DateTime(), DateTime.Parse(WDC_Endiedatum.Value.ToString()),
            ddl_Functie.SelectedValue);

        if (args.IsValid)
        {
            cstV_Endiedatum.ErrorMessage = "Einddatum is overlappend met toegevoegde functies!";
        }
    }

    protected void btn_AddFunc_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            List<ViewZTWFunction> pagefuncList = (List<ViewZTWFunction>)SourceFunctions;

            using (ViewZTWFunction pagefunc = new ViewZTWFunction())
            {
                SourceFunctions = generatePageFunctions(pagefuncList, pagefunc, true);
            }

            SourceGridView.DataSource = pagefuncList;
            SourceGridView.DataBind();

            //if (this.Click != null)
            //{ Click(this, e); }
        }
    }

    protected void btn_UpdateFunc_Click(object sender, EventArgs e)
    {
        if (SourceHiddenRowindex.Value != String.Empty && Page.IsValid)
        {
            //int selectedRowIndex = Convert.ToInt32(HF_RowIndex.Value);

            List<ViewZTWFunction> pagefuncList = (List<ViewZTWFunction>)SourceFunctions;

            SourceFunctions = generatePageFunctions(pagefuncList, pagefuncList[Convert.ToInt32(SourceHiddenRowindex.Value)], false);

            SourceGridView.DataSource = pagefuncList;
            SourceGridView.DataBind();

            //foreach (TableCell extc in gv_Functions.Rows[selectedRowIndex].Cells)
            //{
            //    extc.BackColor = System.Drawing.ColorTranslator.FromHtml("#C1DAD7");
            //}
            btn_UpdateFunc.Enabled = false;
            btn_AddFunc.Enabled = true;

            //if (this.Click != null)
            //{ Click(this, e); }
        }
    }

    /// <summary>
    /// Generated the page functions List
    /// </summary>
    /// <param name="pagefuncList"></param>
    /// <param name="pagefunc"></param>
    /// <param name="addMethod">True: adding; False: updating;</param>
    /// <returns></returns>
    private List<ViewZTWFunction> generatePageFunctions(List<ViewZTWFunction> pagefuncList,
        ViewZTWFunction pagefunc, bool addMethod)
    {
        pagefunc.Functiecode = new CodelijstGegeven(ddl_Functie.SelectedValue, ddl_Functie.SelectedItem.Text, String.Empty);
        pagefunc.GewensteStartdatum = DateTime.Parse(WDC_Ingangsdatum.Value.ToString());
        pagefunc.GewensteEinddatum = DateTime.Parse(WDC_Endiedatum.Value.ToString());

        List<CodelijstGegeven> active = new List<CodelijstGegeven>();
        active.Add(new CodelijstGegeven(ddl_Activiteit.SelectedValue, ddl_Activiteit.SelectedItem.Text, String.Empty));
        pagefunc.Activiteiten = active;

        pagefunc.KlasseCode = new CodelijstGegeven(ddl_Klasse.SelectedValue, ddl_Klasse.SelectedItem.Text, String.Empty);

        if (txt_Number.Text.ToString().Trim() != String.Empty)
        {
            pagefunc.AantalOmgvangOpslagKlasse = txt_Number.Text.ToString().Trim();
            pagefunc.TijdseenheidZorgperiode = new CodelijstGegeven(ddl_timeUnit.SelectedValue);
        }

        pagefunc.Leveringsvorm = new CodelijstGegeven(ddl_IndicationType.SelectedValue, ddl_IndicationType.SelectedItem.Text, String.Empty);

        if (addMethod) { pagefuncList.Add(pagefunc); }

        return pagefuncList;
    }
    #endregion

    #region Private Method
    private String getGridviewRowData(GridViewRow gv_FuncSRow, String lbl_Name)
    {
        return ((Label)gv_FuncSRow.FindControl(lbl_Name)).Text;
    }
    #endregion

    #region Public Method
    /// <summary>
    /// Set the enabled of the inputs Components of functions (Step 4)
    /// </summary>
    /// <param name="status"></param>
    public void ChangeStep4InputsStatus(Boolean status)
    {
        ddl_Functie.Enabled = status;
        WDC_Ingangsdatum.Enabled = status;
        WDC_Endiedatum.Enabled = status;
        ddl_Activiteit.Enabled = status;
        ddl_Klasse.Enabled = status;
        ddl_timeUnit.Enabled = status;
        txt_Number.Enabled = status;

        setTextboxDisabledColor();
    }

    public void changeInputStatusSelectedAddingFunc(GridViewRow gv_FuncSRow)
    {
        ChangeStep4InputsStatus(true);

        WDC_Ingangsdatum.Value = getGridviewRowData(gv_FuncSRow, "lbl_startDate");
        WDC_Endiedatum.Value = getGridviewRowData(gv_FuncSRow, "lbl_endDate");

        ddl_Functie.SelectedValue = gv_FuncSRow.Cells[10].Text;

        bindLists(IBManuallyHandler.GetActivies
                    (ddl_Functie.SelectedValue, SourceIndication.ZZP, ConnectionString),
                ddl_Activiteit);

        bindLists(IBManuallyHandler.GetClasses
                    (ddl_Functie.SelectedValue, ConnectionString),
                ddl_Klasse);

        ddl_Activiteit.SelectedValue = gv_FuncSRow.Cells[11].Text;
        ddl_Klasse.SelectedValue = gv_FuncSRow.Cells[12].Text;

        if (getGridviewRowData(gv_FuncSRow, "lbl_number").ToString().Trim() != String.Empty)
        {
            txt_Number.Text = getGridviewRowData(gv_FuncSRow, "lbl_number");

            if (getGridviewRowData(gv_FuncSRow, "lbl_timeUnit") == "Uren")
            {
                ddl_timeUnit.SelectedValue = "04";
            }

            if (getGridviewRowData(gv_FuncSRow, "lbl_timeUnit") == "Dagdelen")
            {
                ddl_timeUnit.SelectedValue = "13";
            }
        }
        else
        {
            txt_Number.Text = String.Empty;
            ddl_timeUnit.SelectedIndex = -1;
        }
    }
    #endregion
}
